<template>
  <c-form-dialog
    ref="form"
    :visible.sync="innerVisible"
    :table-name="tableName"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    @success="onsuccess"
    @close="handleClose"
    label-width="140px"
    :title="tableId ? '修改客户' : '新增客户'"
  ></c-form-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { idCardValidate, licenseValidate } from '@vimi/utils-tool'
import { phoneValidator } from '@/common/plugins/validator'
import { enumMarrType } from '@/credit/plugins/enum'

import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import SelectAddress from '@/components/select/SelectAddress'
// import SelectIndustrialClass from '@/credit/components/select/SelectIndustrialClass'
import SelectParentMain from '@/bank/views/limit/SelectParentMain'
export default {
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    tableId: String,
    orgType: {
      type: [String, Number],
      default: 1,
    },
  },
  data() {
    const registerValidator = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入统一信用代码'))
      } else if (!licenseValidate(value)) {
        callback(new Error('统一信用代码格式错误!'))
      } else {
        const params = {
          'service_id.eq': this.clientId,
          'submit_type.eq': 2,
          'customer_type.eq': this.orgType,
          'register_no.eq': value,
        }
        const [res] = await this.fetchData(params)
        const data = (res && res.data) || []
        if (data.length && data[0].datum_customer_info_warehouse_id !== this.tableId) {
          callback(new Error('统一信用代码已存在'))
        } else {
          callback()
        }
      }
    }
    const idCardValidator = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入身份证号码'))
      } else if (!idCardValidate(value)) {
        callback(new Error('身份证号错误!'))
      } else {
        if (+this.orgType !== 2) {
          callback()
        }
        const params = {
          'service_id.eq': this.clientId,
          'submit_type.eq': 2,
          'customer_type.eq': this.orgType,
          'id_card.eq': value,
        }
        const [res] = await this.fetchData(params)
        const data = (res && res.data) || []
        if (data.length && data[0].datum_customer_info_warehouse_id !== this.tableId) {
          callback(new Error('身份证号已存在!'))
        } else {
          callback()
        }
      }
    }
    return {
      innerVisible: false,
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '客户名称',
            rules: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
          },
          attrs: { key: 'customer_name', value: '' },
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '经营地址',
            rules: { required: true, message: '请选择经营地址', trigger: 'change' },
          },
          attrs: { key: 'address_code', value: '', class: 'form-control-ml' },
          ifRender: () => {
            return +this.orgType === 1
          },
        },
        {
          tag: 'input',
          itemAttrs: { label: '详细地址' },
          attrs: { key: 'address_detail', value: '', placeholder: '请输入地址' },
          ifRender: () => {
            return +this.orgType === 1
          },
        },
        {
          tag: SelectFarmOrg,
          itemAttrs: {
            label: '组织类型',
            rules: { required: true, message: '请选择组织类型', trigger: 'change' },
          },
          attrs: {
            key: 'org_class',
            value: '',
            placeholder: '组织类型',
            orgType: 1,
            class: 'form-control-ml',
          },
          listeners: {
            select: label => {
              this.org_class_name = label
            },
          },
          ifRender: () => {
            return +this.orgType === 1
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '统一信用代码',
            rules: [{ required: true, validator: registerValidator, trigger: ['change', 'blur'] }],
          },
          attrs: { key: 'register_no', value: '', placeholder: '统一信用代码' },
          ifRender: () => {
            return +this.orgType === 1
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '负责人',
            rules: { required: true, message: '请输入负责人', trigger: 'blur' },
          },
          attrs: { key: 'corp_name', value: '', placeholder: '负责人' },
          ifRender: () => {
            return +this.orgType === 1
          },
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '家庭地址',
            rules: { required: true, message: '请选择家庭地址', trigger: 'change' },
          },
          attrs: { key: 'family_address_code', value: '', class: 'form-control-ml' },
        },
        {
          tag: 'input',
          itemAttrs: { label: '详细地址' },
          attrs: { key: 'family_address_code_detail', value: '', placeholder: '请输入地址' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证号',
            rules: [{ required: true, validator: idCardValidator, trigger: ['change', 'blur'] }],
          },
          attrs: { key: 'id_card', value: '', placeholder: '负责人身份证' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'mobile_no', value: '', placeholder: '联系电话' },
        },
        {
          tag: 'c-select',
          itemAttrs: {
            label: '婚姻状况',
            rules: { required: true, message: '请选择婚姻状况', trigger: 'change' },
          },
          attrs: {
            key: 'marriage_status',
            placeholder: '请选择婚姻状况',
            options: enumMarrType,
            class: 'form-control-ml',
          },
          ifRender: () => {
            return +this.orgType === 2
          },
        },
        // {
        //   tag: 'c-select',
        //   itemAttrs: {
        //     label: '主营产业'
        //   },
        //   attrs: {
        //     key: 'main_business',
        //     value: '',
        //     class: 'form-control-ml',
        //     placeholder: '请选择主营产业',
        //     props: { value: 'label', label: 'label' },
        //     options: IndustryTypeArray
        //   }
        // },
        {
          tag: SelectParentMain,
          itemAttrs: {
            label: '行业分类',
          },
          attrs: {
            key: 'ind_class_code',
            value: '',
            class: 'form-control-ml',
            placeholder: '请选择行业分类',
          },
          listeners: {
            select: (_, item) => {
              this.selectIndCalss = item
            },
          },
        },
        {
          tag: 'textarea',
          itemAttrs: {
            label: '经营范围',
          },
          attrs: {
            key: 'business_scope',
            value: '',
            autosize: { minRows: 3 },
            placeholder: '请输入经营范围',
          },
        },
      ],
      tableName: 'datum_customer_info_warehouse',
      registerNo: true,
      idCard: true,
      org_class_name: '',
      selectIndCalss: {},
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      // if (val) {
      //   this.$refs.form.setAttrs('register_no', { disabled: !!this.tableId })
      //   if (+this.orgType === 2) {
      //     this.$refs.form.setAttrs('id_card', { disabled: !!this.tableId })
      //   }
      // }
    },
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  created() {},
  methods: {
    fetchData(params) {
      return this.$utils.promise(this.$api.getData(this.$serviceName, this.tableName, params))
    },
    handleBeforeSave(data) {
      // const industry = IndustryTypeArray.find(item => item.label === data.main_business)
      // if (industry) {
      //   data.parent_main_business = enumParentBusiness[industry.parent]
      // }
      data.customer_type = this.orgType
      data.service_id = this.clientId
      data.org_class_name = this.org_class_name || data.org_class_name
      data.submit_type = 2
      if (+this.orgType === 2) {
        data.org_class = 'org_farmer'
        data.org_class_name = '个人'
        data.address_code = data.family_address_code
        data.address_detail = data.family_address_code_detail
      }

      // 行业分类
      const { selectIndCalss } = this
      data.ind_class_name = selectIndCalss.value || ''

      return data
    },
    handleClose() {
      this.$emit('update:visible', false)
    },
    onsuccess() {
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
